dsu greedy strings *1500

Please click on ads to support us..

Python Code:

from collections import defaultdict
import sys
input = sys.stdin.readline

def inp():
    return(int(input()))
def inlt():
    return(list(map(int,input().split())))
def insr():
    s = input()
    return(list(s[:len(s) - 1]))
def invr():
    return(map(int,input().split()))
def compress(root, x):
    if root[x] == x:
        return x
    
    root[x] = compress(root, root[x])
    return root[x]
t = inp()
for _ in range(t):
    n, k = inlt()
    _dict = defaultdict(list)
    s = input()
    if s[-1] == '\n':
        s = s[:len(s) - 1]
    s = list(s)
    root = [i for i in range(26)]
    index = 0
        while k > 0 and index < len(s):
        ch = s[index]
        idx = ord(ch) - ord('a')
        compress(root, idx)
        
                if root[idx] > 0:
            root[idx] = idx - 1
                        s[index] = chr(root[idx] + ord('a'))
            k -= 1
        else:
            index += 1
    ans = ''
    for ch in s:
        idx = ord(ch) - ord('a')
        changed = compress(root, idx)
        ans += chr(changed + ord('a'))
    print(ans)
        
    

C++ Code:

#include<bits/stdc++.h>
using namespace std;
int n,k;
string s;
void solve()
{
	cin>>n>>k>>s;
	int now=0,tw=-1,m;
	for(int i=0;i<n;i++)
	{
		if(s[i]-'a'<=k) 
		{
			now=max(now,s[i]-'a');
			s[i]='a';
		}
		else 
		{
			if(tw==-1)
			{
				tw=s[i]-'a';
				m=s[i]-(k-now)-'a';
			}
			k=now;
			if(s[i]-'a'<=tw && s[i]-'a'>=m)
			{
				s[i]='a'+m;
			}
		}
	}
	cout<<s<<endl;
}
signed main()
{
    int _=1;
    cin>>_;
    while(_--)
    {
    	solve();
    }
}


Comments

Submit
0 Comments
More Questions

49A - Sleuth
1541A - Pretty Permutations
1632C - Strange Test
673A - Bear and Game
276A - Lunch Rush
1205A - Almost Equal
1020B - Badge
1353A - Most Unstable Array
770A - New Password
1646B - Quality vs Quantity
80A - Panoramix's Prediction
1354B - Ternary String
122B - Lucky Substring
266B - Queue at the School
1490A - Dense Array
1650B - DIV + MOD
1549B - Gregor and the Pawn Game
553A - Kyoya and Colored Balls
1364A - XXXXX
1499B - Binary Removals
1569C - Jury Meeting
108A - Palindromic Times
46A - Ball Game
114A - Cifera
776A - A Serial Killer
25B - Phone numbers
1633C - Kill the Monster
1611A - Make Even
1030B - Vasya and Cornfield
1631A - Min Max Swap